﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;
using LiteExpress.Core;
using Castle.DynamicProxy;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Extras.DynamicProxy2;

namespace LiteExpress.Core.WebDemo
{
    public class ServiceConfig
    {
        public static void RegisterTypes()
        {
            ContainerManager.UpdateContainer(builder =>
            {
                builder.RegisterAssemblyTypes(
                System.Reflection.Assembly.Load("LiteExpress.Demo.Data")
                ).Where(t => t.Name.EndsWith("Adapter")).AsImplementedInterfaces()
                .EnableInterfaceInterceptors()//此方法需要引入Autofac.Extras.DynamicProxy2;命名空间
               .InterceptedBy(typeof(TestLogger));//aop拦截

                builder.RegisterAssemblyTypes(
                    System.Reflection.Assembly.Load("LiteExpress.Demo.Business")
                    ).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();

                builder.Register(c => new TestLogger());

                builder.RegisterControllers(typeof(MvcApplication).Assembly);//注册控制器                
            });
            DependencyResolver.SetResolver(new AutofacDependencyResolver(ContainerManager.Container));
        }

        #region aop
        public class TestLogger : IInterceptor
        {
            public TestLogger()
            {
            }

            public void Intercept(IInvocation invocation)
            {
                //System.Diagnostics.Debug.WriteLine("Calling method {0} with parameters {1}",
                //    invocation.Method.Name,
                //    string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()));

                //try
                //{
                    invocation.Proceed();
                //}
                //catch (Exception ex)
                //{
                //    var e = GetInnerException(ex);
                //    System.Diagnostics.Debug.WriteLine("exception:" + e.ToString() + e.StackTrace);
                //}

                //System.Diagnostics.Debug.WriteLine("Done: result was {0}.", invocation.ReturnValue);
            }
        }

        /// <summary>
        /// 获取内层的exception
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private static Exception GetInnerException(Exception ex)
        {
            Exception result = ex;
            while (result.InnerException != null)
            {
                result = result.InnerException;
            }
            return result;
        }
        #endregion
    }
}